package com.itgaohe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itgaohe.common.context.UserContext;
import com.itgaohe.dao.entity.BlogComments;
import com.itgaohe.dao.entity.User;
import com.itgaohe.dao.mapper.BlogCommentsMapper;
import com.itgaohe.dao.mapper.UserMapper;
import com.itgaohe.dto.resp.SearchBlogCommentDTO;
import com.itgaohe.service.BlogCommentsService;
import com.itgaohe.utils.CreateCursorUtil;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BlogCommentsServiceImpl extends ServiceImpl<BlogCommentsMapper, BlogComments> implements BlogCommentsService {
    @Autowired
    private BlogCommentsMapper blogCommentsMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<SearchBlogCommentDTO> getCommentsByBlogId(long blogid) {
        //创建SearchBlogCommentDTO 集合
        List<SearchBlogCommentDTO> searchBlogCommentDTOS = new ArrayList<>();
        //查询BlogComments
        LambdaQueryWrapper<BlogComments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlogComments::getBlogId, blogid);
        List<BlogComments> blogComments = blogCommentsMapper.selectList(queryWrapper);
        //创建SearchBlogCommentDTO类
        SearchBlogCommentDTO searchBlogCommentDTO = new SearchBlogCommentDTO();


        //遍历BlogComments
        blogComments.forEach(blogComment -> {
            //查询user
            User user = userMapper.selectById(blogComment.getUserId());
            //封装searchBlogCommentDTO类
            searchBlogCommentDTO.setUserId(blogComment.getUserId());
            searchBlogCommentDTO.setContent(blogComment.getContent());
            searchBlogCommentDTO.setName(user.getNickName());
            searchBlogCommentDTO.setIcon(user.getIcon());
        });
        // SearchBlogCommentDTO集合中添加数据
        searchBlogCommentDTOS.add(searchBlogCommentDTO);
        return searchBlogCommentDTOS;
    }

    @Override
    public boolean addBlogComment(BlogComments blogComments) {
        Long userId = UserContext.getUser().getId();
        blogComments.setUserId(userId);
        blogComments.setCursorIndex(CreateCursorUtil.getNormalCursor(userId));
        int insert = blogCommentsMapper.insert(blogComments);
        if (insert != 0) {
            return true;
        }
        return false;
    }
}
